package com.b2c.erp.controller.shop;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.b2c.entity.api.ApiResult;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.tao.TaoMarketingFeeEntity;
import com.b2c.entity.tao.TrafficTaoModel;
import com.b2c.erp.controller.CommonControllerUtils;
import com.b2c.erp.controller.funds.MarketingCostImportSubmitReq;
import com.b2c.interfaces.WmsUserService;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.erp.DataConfigObject;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.ShopTrafficGoodsService;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping("/shop")
@Controller
public class ShopTrafficTaoController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopTrafficGoodsService shopTrafficGoodsService;
    @Autowired
    private WmsUserService manageUserService;
    Logger log = LoggerFactory.getLogger(ShopTrafficTaoController.class); 

    @RequestMapping(value = "/shop_traffic_tao", method = RequestMethod.GET)
    public String shopTrafficPdd(Model model, HttpServletRequest request) {
        Integer shopType = 4;
      
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }
        // 店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(null, shopType);
        model.addAttribute("shops", shops);


        Integer shopId=6;
        if (!StringUtils.isEmpty(request.getParameter("shopId"))){
            shopId = Integer.parseInt(request.getParameter("shopId")); 
        }
        model.addAttribute("shopId",shopId);
        String date =null;
        if(StringUtils.hasText(request.getParameter("date"))){
            date = request.getParameter("date");
            model.addAttribute("date", date);
        }
        

        var result = shopTrafficGoodsService.getShopTrafficList(pageIndex, 100, shopType, shopId,date);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

//        model.addAttribute("view", "taotraffic");
//        model.addAttribute("pView", "tao");
        CommonControllerUtils.setViewKey(model,manageUserService,"taoshop");
        return "eshop/shop_traffic_tao";
    }

    @RequestMapping(value = "/goods_traffic_tao", method = RequestMethod.GET)
    public String listTao(Model model, HttpServletRequest request) {
        Integer shopType = 4;
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }
        // 店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(null, shopType);
        model.addAttribute("shops", shops);

        String goodsNum = null;
        if(StringUtils.hasText(request.getParameter("goodsNum"))){
            goodsNum = request.getParameter("goodsNum");
            model.addAttribute("goodsNum", goodsNum);
        }
        Integer shopId=6;
        if (!StringUtils.isEmpty(request.getParameter("shopId"))){
            shopId = Integer.parseInt(request.getParameter("shopId"));
        }
        model.addAttribute("shopId",shopId);
        String date = null;//DateUtil.customizeDate_(1);
        // date = request.getParameter("date");

        if(StringUtils.hasText(request.getParameter("date"))){
            date = request.getParameter("date");
        }
        model.addAttribute("date", date);

        var result = shopTrafficGoodsService.getGoodsTrafficList(pageIndex, 100, shopType, shopId, goodsNum,date);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

//        model.addAttribute("view", "taotraffic");
//        model.addAttribute("pView", "tao");
        CommonControllerUtils.setViewKey(model,manageUserService,"taoshop");
        return "eshop/shop_goods_traffic_tao";
    }


    @RequestMapping("/goods_traffic_tao_import")
    public String execlImport(Model model, HttpServletRequest request) {
        Integer userId = DataConfigObject.getInstance().getLoginUserId();
        String date = null;
        if(StringUtils.hasText(request.getParameter("date"))){
            date = request.getParameter("date");
            model.addAttribute("date", date);
        }
        // 有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId, 4);// type=4是tao
        model.addAttribute("shops", shops);
        model.addAttribute("shopId", 6);
        model.addAttribute("view", "taotraffic");
        model.addAttribute("pView", "tao");
        return "tao/goods_traffic_tao_import";
    }

    @ResponseBody
    @RequestMapping(value = "/goods_traffic_tao_import_ajax", method = RequestMethod.POST)
    public ApiResult<List<TrafficTaoModel>> orderSendExcel(@RequestParam("excel") MultipartFile file,
                                                                 HttpServletRequest req) throws IOException, InvalidFormatException {
        Integer shopId = Integer.parseInt(req.getParameter("shopId"));
        String date = req.getParameter("date");
        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
        //System.out.println(destFileName);
        File destFile = new File(destFileName);
        if(destFile.exists()){
            destFile.deleteOnExit();
        }
        file.transferTo(destFile);
        log.info("/***********导入商品流量数据{shopId:"+shopId+",date:"+date+"}，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");
        InputStream fis = null;
        fis = new FileInputStream(destFileName);
        if (fis == null)
            return new ApiResult<>(502, "没有文件");

        Workbook workbook = null;

        try {
            if (fileName.toLowerCase().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (fileName.toLowerCase().endsWith("xls")) {
                workbook = new HSSFWorkbook(fis);
            }
            // workbook = new HSSFWorkbook(fis);
        } catch (Exception ex) {
            log.info("/***********导入商品流量数据***出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        if (workbook == null)
            return new ApiResult<>(502, "未读取到Excel文件");

        fis.close();
        if(destFile.exists()){
            log.info("删除导入的文件。。。。。。。");
            boolean s = destFile.delete();
            System.out.println(s);
        }




        /**************** 开始处理批批网csv订单 ****************/
        // 订单list
        Sheet sheet = null;
        List<TrafficTaoModel> lists = new ArrayList<>();
        boolean hasSheet = true;
        int sheetIndex = 0;

        while (hasSheet){
            try {
                sheet = workbook.getSheetAt(sheetIndex);
                int startRow = (sheetIndex+1)*10000;
                int l = sheet.getLastRowNum();
                if(l==-1) {
                    hasSheet = false;
                    continue;
                }
                getData(sheet,lists,date,startRow);
                sheetIndex++;
            }catch (Exception e){
                hasSheet = false;
            }
        }
        return new ApiResult<>(0, "SUCCESS", lists);

    }

    @ResponseBody
    @RequestMapping(value = "/goods_traffic_tao_import_submit", method = RequestMethod.POST)
    public ApiResult<String> orderExcelImportSubmit(@RequestBody MarketingCostImportSubmitReq<TrafficTaoModel> req) {
        if (req.getShopId() == null || req.getShopId() == 0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有shopId");

        List<TrafficTaoModel> lists = req.getList();
        if (lists == null || lists.size() == 0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有orderList");

        Integer shopId = req.getShopId();

//        return new ApiResult<>(0, "SUCCESS");

        ResultVo<String> resultVo = shopTrafficGoodsService.addGoodsTrafficTao(req.getList(), shopId);

        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
            return new ApiResult<>(0, "SUCCESS", resultVo.getData());
        } else
            return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());

    }

    private void getData(Sheet sheet, List<TrafficTaoModel> lists, String date,int startRow){
        try {
            int lastRowNum = sheet.getLastRowNum();// 最后一行索引
            Row row = null;
            int dataIndex = 1;
            int dataSize = 6;
            boolean isNext = true;

            while (isNext){
                //开始
                int start = (dataIndex - 1 ) * dataSize + 1;
                row = sheet.getRow(start);
                if(row == null)
                {
                    isNext = false;
                    continue;
                }
                //读取支付金额、支付买家数、商品加购人数、商品收藏人数、商品访客
                BigDecimal payAmount = BigDecimal.valueOf(row.getCell(1).getNumericCellValue());
                Double buyers = row.getCell(2).getNumericCellValue();
                Double carts =  row.getCell(3).getNumericCellValue();
                Double colls =  row.getCell(4).getNumericCellValue();
                Double views =  row.getCell(5).getNumericCellValue();
                //读取商品标题
                Row titleRow = sheet.getRow(start+1);
                String title = titleRow.getCell(0).getStringCellValue();
                //读取商品id
                Row idRow = sheet.getRow(start+2);
                String goodsId = idRow.getCell(0).getStringCellValue();
                goodsId = goodsId.replace("ID:","").replace("较上一周期","");
                TrafficTaoModel m = new TrafficTaoModel();
                m.setGoodsId(goodsId);
                m.setTitle(title);
                m.setPayAmount(payAmount);
                m.setBuyers(buyers);
                m.setCarts(carts);
                m.setColls(colls);
                m.setViews(views);
                m.setDate(date);
                m.setId(startRow + start);
                lists.add(m);
                dataIndex ++;
            }


        } catch (Exception ex) {
            log.info("/***********导入tao营销费用数据****出现异常：" + ex.getMessage() + "***********/");
        }
    }



}
